from . import view
from . import schema
from fastapi import APIRouter, Depends, Security
from package.connector.sql_db import db
from package.fastapi import permission
from model.model import Enum

router_enum = APIRouter(prefix='/enum', tags=['系统枚举'])
router_meta = {'module': '系统管理', 'sub_module': '系统枚举'}


@router_enum.get('/', response_model=schema.PageEnumOut, openapi_extra=router_meta, name='enum_list_get',
                 summary='枚举列表')
def enum_get(q: str = None,
             page: int = 1,
             page_size: int = 10,
             order_by: str = 'created_at desc',
             session=Depends(db.get_session),
             user=Security(permission.security, scopes=['enum:read'])):
    return Enum.get_page_items(session, q=q, page=page, page_size=page_size, order_by=order_by)


@router_enum.post('/', response_model=schema.EnumOut, openapi_extra=router_meta, name='enum_post', summary='枚举创建')
def user_post(body: schema.Enum,
              session=Depends(db.get_session),
              user=Security(permission.security, scopes=['enum:write'])):
    return Enum.create_item(session, body=body.dict())


@router_enum.get('/{name}', response_model=schema.EnumOut, openapi_extra=router_meta, name='enum_get',
                 summary='枚举详情')
def enum_get(name: str,
             session=Depends(db.get_session),
             user=Security(permission.security, scopes=['enum:read'])):
    return Enum.get_item(session, filter_=[Enum.name == name])


@router_enum.patch('/{name}', response_model=schema.EnumOut, openapi_extra=router_meta, name='enum_patch',
                   summary='枚举修改')
def enum_patch(name: str,
               body: schema.EditEnum,
               session=Depends(db.get_session),
               user=Security(permission.security, scopes=['enum:write'])):
    return Enum.update_item(session, filter_=[Enum.name == name], update=body.dict(exclude_unset=True))


@router_enum.delete('/', openapi_extra=router_meta, name='enum_delete', summary='枚举删除')
def enum_delete(body: schema.BatchName,
                session=Depends(db.get_session),
                user=Security(permission.security, scopes=['enum:write'])):
    return {'count': Enum.delete_items(session, filter_=[Enum.name.in_(body.names)])}
